package com.heiam.search.service.impl;

import com.heiam.search.pojo.ApUserSearch;
import com.heiam.search.service.ApUserSearchService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDto;
import com.heima.model.user.entity.ApUser;
import com.heima.utils.common.threadUtil.ThreadLocalUtil;
import com.heima.utils.common.threadUtil.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Resource
    private MongoTemplate mongoTemplate;
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        if(apUserSearch==null){
        //当前无此搜索历史
            apUserSearch=new ApUserSearch();
            apUserSearch.setUserId(userId.intValue());
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setKeyword(keyword);

            //查询当前历史记录
            Query query1 = Query.query(Criteria.where("userId").is(userId));
            //根据创建时间倒序排序
            query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
            List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);
            if(apUserSearchList==null||apUserSearchList.size()<10){
                mongoTemplate.insert(apUserSearch);
            }else{
                //从集合中获取最后一个历史记录--记录时间最早
                ApUserSearch lastSearch = apUserSearchList.get(apUserSearchList.size() - 1);

                mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastSearch.getId())),apUserSearch);

            }
            return ;
        }
        //由此搜索记录,更新时间
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);
    }

    @Override
    public ResponseResult finUserSearch() {

        //获取当前用户id
        UserInfo userInfo = ThreadLocalUtil.get();
        if(userInfo==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userInfo.getId())).with(Sort.by(Sort.Direction.DESC,"createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(searchList);
    }

    /**
     * 删除历史记录
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {

        //参数校验
        if(historySearchDto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断是否登录
        UserInfo userInfo = ThreadLocalUtil.get();
        if(userInfo==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.删除历史记录
        mongoTemplate.remove(Query.query(Criteria.where("id").is(userInfo.getId())),ApUserSearch.class);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
